package com.shell.selectclass;

import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private RadioGroup radioGroup; //单选框
    private TextView textView; //下方提示信息
    private LinearLayout linearCheckbox; //包含所有复选框的LinearLayout

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    void init() {
        radioGroup = (RadioGroup) findViewById(R.id.radio);
        textView = (TextView) findViewById(R.id.textView2);//空白文本框
        linearCheckbox = (LinearLayout) findViewById(R.id.linearCheckbox);//获取所有的复选框
        //提交按钮
        Button sub = (Button) findViewById(R.id.btu_sub);
        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = radioGroup.getChildCount();
                RadioButton radioButton;
                String major = "你没有选择专业";
                for (int i = 0; i < count; i++) {
                    radioButton = (RadioButton) radioGroup.getChildAt(i);
                    if (radioButton.isChecked()) {
                        major = radioButton.getText().toString();
                        break;
                    }

                }
                StringBuilder txt = new StringBuilder();
                int countCheckbox = linearCheckbox.getChildCount();//复选框的数目。
                CheckBox checkBox = null;
                for (int i = 0; i < countCheckbox; i++) { //i用于遍历复选框
                    checkBox = (CheckBox) linearCheckbox.getChildAt(i); //获取复选框
                    if (checkBox.isChecked()) {
                        txt.append("  ").append(checkBox.getText().toString());
                    }
                }
                textView.setText("你提交的专业是：" + major + "\n你提交的课程是：" + txt);
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                String major = radioButton.getText().toString();
//                textView.setText("选择的专业是：" + major);
                Toast.makeText(MainActivity.this, ("你选择的专业是：" + major), Toast.LENGTH_LONG).show();
            }
        });


    }
}
